
<template>
  <el-form :model="formData" :inline="modelValue.inline" :label-position="modelValue.labelPosition" label-suffix=":"
           :rules="rules" :label-width="modelValue.labelWidth" ref="baseForm" @submit.native.prevent>
    <!-- 搜索项容器 -->
    <div class="search-items" :class="{ 'auto-fit': modelValue.autoFit }"
         :style="modelValue.autoFit ? {} : { flexWrap: 'wrap' }">
      <!-- <input type="hidden" name="test" value="123" /> -->
      <!-- 动态生成搜索项 -->

      <template v-for="(item, index) in modelValue.items.filter(value => !value.isHidden)" :key="index">
        <el-form-item :prop="item.field" :label="item.label"
                      :label-width="item.labelWidth || modelValue.labelWidth || '100px'"
                      :style="{ flex: modelValue.autoFit ? '1' : 'unset', gridColumn: item.span ? `span ${item.span}` : '' }"
                      class="form-item">


          <template v-if="item.type === FORM_FIELD_TYPE.INPUT && item.labelField">
            <el-input v-show="false" style="width: 100%"  v-model="formData[item.field]"
                      v-bind="item.props" :placeholder="item.placeholder" :type="item?.type === 'textarea' ? 'textarea': 'text'"
                      :disabled="item.config?.disabled || false" />

            <el-input style="width: 100%" v-model="formData[item.labelField]"
                      v-bind="item.props" :placeholder="item.placeholder" :type="item?.type === 'textarea' ? 'textarea': 'text'"
                      @click="formItemClick(item)"
                      :disabled="item.config?.disabled || false" />
          </template>

          <el-input style="width: 100%" v-else-if="item.type === FORM_FIELD_TYPE.INPUT" v-model="formData[item.field]"
                    v-bind="item.props" :placeholder="item.placeholder" :type="item?.type === 'textarea' ? 'textarea': 'text'"
                    @click="formItemClick(item)"
                    :disabled="item.config?.disabled || false" />
          <el-input style="width: 100%" v-else-if="item.type === FORM_FIELD_TYPE.TEXTAREA" v-model="formData[item.field]"
                    v-bind="item.props" :placeholder="item.placeholder" type="textarea"
                    @click="formItemClick(item)"
                    :disabled="item.config?.disabled || false" />

          <el-switch style="width: 100%" v-else-if="item.type === FORM_FIELD_TYPE.SWITCH" v-model="formData[item.field]"
                     v-bind="item.props" />

          <el-rate style="width: 100%" v-else-if="item.type === FORM_FIELD_TYPE.RATE" v-model="formData[item.field]"
                   v-bind="item.props" />

          <el-checkbox style="width: 100%" v-else-if="item.type === FORM_FIELD_TYPE.CHECKBOX"
                       v-model="formData[item.field]" v-bind="item.props" />

          <el-checkbox-group v-else-if="item.type === FORM_FIELD_TYPE.CHECKBOX_GROUP" v-model="formData[item.field]">
            <el-checkbox :key="item.value" v-for="item in item.config.options" :label="item.label"
                         :value="item.value" />
          </el-checkbox-group>


          <el-radio-group v-model="formData[item.field]" v-else-if="item.type === FORM_FIELD_TYPE.RADIO">
            <el-radio :key="item.value" v-for="item1 in item.config.options"
                      :value="item1[item.config?.value ? item.config?.value : 'value']">
              {{ item1[item.config?.label || 'label'] }}
            </el-radio>
          </el-radio-group>



          <el-date-picker style="width: 100%" v-else-if="item.type === FORM_FIELD_TYPE.DATE"
                          v-model="formData[item.field]" :type="item.type" v-bind="item.props" />
          <el-date-picker style="width: 100%" v-else-if="item.type === FORM_FIELD_TYPE.DATETIME"
                          :value-format="item.config && item.config.valueFormat || 'YYYY-MM-DD HH:mm:ss'"
                          v-model="formData[item.field]" :type="item.type" v-bind="item.props" />
          <el-date-picker style="width: 100%" v-else-if="item.type === FORM_FIELD_TYPE.DATE_RANGE"
                          v-model="formData[item.field]" :type="item.type" range-separator="至" start-placeholder="开始日期"
                          value-format="YYYY-MM-DD" end-placeholder="结束日期" v-bind="item.props" />
          <el-date-picker style="width: 100%" v-else-if="item.type === FORM_FIELD_TYPE.DATE_TIME_RANGE"
                          v-model="formData[item.field]" :type="item.type" range-separator="至" start-placeholder="开始日期"
                          value-format="YYYY-MM-DD" end-placeholder="结束日期" v-bind="item.props" />



          <CommonSelect v-else-if="item.type === FORM_FIELD_TYPE.SELECT" :config="item.config"
                        :placeholder="item.placeholder"
                        v-model="formData[item.field]" />



          <CommonTree :config="item.config"
                      v-else-if="item.type === FORM_FIELD_TYPE.TREE"
                      v-model="formData[item.field]" />


          <upload-basic v-model="formData[item.field]" :config="item.config"
                        v-else-if="item.type === FORM_FIELD_TYPE.UPLOAD" />


          <div v-else-if="item.type === FORM_FIELD_TYPE.EDITOR" style="height: 500px">

            <toolbar :editor="editorRef" style="border-bottom: 1px solid var(--el-border-color)" />
            <editor v-model="formData[item.field]" class="wang-editor-content" :default-config="editorConfig"
                    @on-created="handleCreated" />
          </div>

          <div v-else-if="item.type === FORM_FIELD_TYPE.INPUTNUMBER">
            <el-input-number v-model="formData[item.field]"
                             :min="item.config?.min || item.config?.min == 0 ? item.config?.min : -999999"
                             :max="item.config?.max ? item.config?.max : 10000000000" :step="item.config?.step ? item.config?.step : 1"
                             :controls-position="item.config?.position ? 'right' : ''" />
          </div>
        </el-form-item>
      </template>
    </div>
  </el-form>
  <div style="padding-top: 20px;text-align: right" v-if="!(modelValue.hideButton == true)">

    <el-button  @click="item['click'](item)" v-for="item in modelValue.buttons">{{item.name}}</el-button>
    <el-button type="primary" @click="handleSave" :icon="Search">保存</el-button>
    <el-button @click="handleReset" :icon="Refresh">重置</el-button>
  </div>

</template>

<script setup>
import { Search, Sort, Refresh } from '@element-plus/icons-vue'
import FORM_FIELD_TYPE from '/@/constants/FormFieldType'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
const baseForm = ref(null)
const props = defineProps({
  modelValue: {
    type: Object,
    required: true
  }
})
const columnCount = props.modelValue.columnCount || '6'
const columnWidth = props.modelValue.columnWidth || '300px'
const emits = defineEmits(['search', 'save', 'update:modelValue'])
const formData = ref({});
const editorConfig = reactive({
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: '', // 您的服务器地址，注意：当前接口格式特殊与其他vab接口不同，请查看vip文档
      fieldName: 'vab-file-name',
      allowedFileTypes: ['image/*'],
      headers: {}, // 如需传递token请写到在这里
    },
  },
})
const rules = ref({})

for (let item of props.modelValue.items) {
  rules.value[item.field] = item.rule
}

const editorRef = shallowRef()
const handleCreated = (editor) => {
  editorRef.value = editor
}

// 搜索按钮事件
const handleSave = () => {

  baseForm.value?.validate(async (valid) => {



    if (valid) {
      //   emits('save', formData.value) //触发父类事件
      if (props.modelValue.callback) {
        let baseFormKey = Object.keys(formData.value);
        // 显示字符信息的字段要去除掉
        let labelField = props.modelValue.items.filter((item) =>item.labelField).map(item=>item.labelField);
        if (labelField.length === 0) {
          props.modelValue.callback(JSON.parse(JSON.stringify(formData.value)));
        } else {

          let result = {}
          for (let key of baseFormKey) {
            if (!labelField.includes(key)) {
              result[key] = formData.value[key]
            }
          }
          props.modelValue.callback(result);
        }


      }
    }
  })

};


watch(() => props.modelValue.modelData, (data) => {
  initData(data)
}, { deep: true });


const initData = (data) => {
  let fieldList = props.modelValue.items.map(value => value.field);
  for (let key of Object.keys(data)) {
    formData.value[key] = data[key]
    if (data[key] == null && fieldList.indexOf(key) !== -1) {
      let item = props.modelValue.items.filter(value => value.field == key)
      if (item) {
        let target = item[0]
        if (target && target.config) {
          if (target.config.defaultValue != undefined) {
            formData.value[key] = target.config.defaultValue
          } else {

            if (target.config.optionsFunction) {
              let data = target.config.optionsFunction()
              console.log(data);
              if (data && data.length > 0) {
                let item = data[0]
                formData.value[key] = target.config['prop'] ? item[target.config['prop']['value']] :item['value']
              }
            }

          }
        }
      }
    }
  }
}
initData(props.modelValue.modelData)
// 重置按钮事件
const handleReset = () => {
  props.modelValue.items.forEach((item) => {
    if (item.type === FORM_FIELD_TYPE.SELECT) {
      formData.value[item.field] = [];
    } else {
      formData.value[item.field] = item.defaultValue || null;
    }
  });
};


const formItemClick = (item)=> {
  if (props.modelValue && props.modelValue.formItemClick) {
    props.modelValue.formItemClick(item)
  }
}
</script>

<style scoped>
.search-items {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  max-height: 800px;
  overflow: auto;
}

.form-item {
  /* 每个表单项的默认样式 */
}





/* 当没有autoFit且指定了列数时，保持grid列数不变 */
.search-items {
  display: grid;
  gap: 8px 16px;
  grid-template-columns: repeat(v-bind(columnCount), 1fr);
  /* 固定列数 */
}

.search-items.auto-fit {
  display: grid;
  gap: 8px 16px;
  grid-template-columns: repeat(auto-fill, minmax(v-bind(columnWidth), 1fr));
  /* 自适应列数 */
}

/* 隐藏第三行之后的元素 */
.search-items:nth-child(n + 10) {
  display: none;
}


::v-deep(.el-form-item--default) {
  margin-bottom: 0;
}

::v-deep(.is-fullscreen) {
  color: red;
}
</style>
